<?php
namespace app\common\bonus;

class Action
{

	private $error;
	private $action_name;
	private $data;
	private $model;

	public function getError(){
		return $this->error;
	}

	public function __construct($action_name,$operate_id=null){
		$this->action_name = strtolower($action_name);
		$model = model('bonus_action');
		$this->model = $model;
		// 消息队列
		if(is_null($operate_id)){
			$this->data = $model->getDatas(['action_name'=>$action_name,'status'=>0]);
		}else{
			$this->data = $model->getDatas(['action_name'=>$action_name,'operate_id'=>$operate_id,'status'=>0]);
		}
	}

	public function deal(){
		$action_name = '\\app\common\bonus\\'.ucfirst($this->action_name);
		$dataList = $this->data;
		if(empty($dataList)){
			return true;
		}

		$handler = new $action_name;

		$memberScoreModel = model('member_score');
		foreach($dataList as $value):
			// member_score日志Log记录
			$log = $memberScoreModel -> where('id',$value['operate_id'])->value('log');
			$log .= date("Y-m-d H:i:s").'正在处理'.$action_name."奖金;\n";
			$memberScoreModel -> save(['log'=>$log,],['id'=>$value['operate_id']]);
			// 锁消息表
			$this->model->save(['status'=>3],['id'=>$value['id']]);

			$value['action_data'] = unserialize($value['action_data']);
			// 处理消息
			$result = $handler->handle($value);
			if(false===$result){
				$remark = $handler->getError();
				$this->model->where(['id'=>$value['id']])->update(['status'=>2,'remark'=>$remark]);
			}else{
				$remark = '处理成功';
				$this->model->where(['id'=>$value['id']])->update(['status'=>1,'remark'=>$remark]);
				// 删除消息队列记录
			}
			$log = $memberScoreModel -> where('id',$value['operate_id'])->value('log');
			$log .= date("Y-m-d H:i:s").'处理'.$action_name.'['.$remark."];\n";
			$memberScoreModel -> save(['log'=>$log],['id'=>$value['operate_id']]);
		endforeach;

		return true;
	}

}